package com.dongdong.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.dongdong.data.Result;
import com.dongdong.em.ResultEmnu;
import com.dongdong.pojo.TbSeckillGoods;
import com.dongdong.pojo.TbUser;
import com.dongdong.service.SeckillService;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("seckillContoller")
public class SeckillController {
    @Reference(timeout = 50000)
    private SeckillService seckillService;
    @RequestMapping("loLogin")
    public String loLogin(){
        return "login";
    }
    @RequestMapping("seckillIndex")
    public String toSeckillIndex(Model model){
        List<TbSeckillGoods> seckillGoodsList =  seckillService.selectAll();
        model.addAttribute("seckillGoodsList",seckillGoodsList);
        return "seckill-index";
    }
    @RequestMapping("findGoodsById/{id}")
    public String findGoodsById(@PathVariable("id")Long id,Model model) {
       TbSeckillGoods seckillGoods =  seckillService.findGoodsById(id);
       if (seckillGoods == null){
           return "sale-over";
       }
       model.addAttribute("seckillGoods",seckillGoods);
        return "seckill-item";
    }
    @RequestMapping("ohMyGod")
    @ResponseBody
    public Result ohMyGod(Long id){
        TbUser user = (TbUser)SecurityUtils.getSubject().getPrincipal();
        if (user == null){
            return  Result.respone(ResultEmnu.NOLOGIN);
        }
        try{
            seckillService.createOrder(id,user.getUsername());

        }catch (Exception e){
            e.printStackTrace();
            return Result.respone(ResultEmnu.SALE_OVER);
        }
        return Result.respone(ResultEmnu.SUCCESS);
    }
    @RequestMapping("getOrderId")
    @ResponseBody
    public Result getOrderId(){
        TbUser user = (TbUser) SecurityUtils.getSubject().getPrincipal();
        Long orderId = seckillService.getOrderId(user.getUsername());
        return Result.respone(ResultEmnu.SUCCESS).setData(orderId);
    }
}
